//
//  GLTollStationDataListViewController.m
//  Runone
//
//  Created by ekkaLyn on 2017/4/20.
//  Copyright © 2017年 runone. All rights reserved.
//

#import "GLTollStationDataListViewController.h"
#import "GLTollStationDataCell.h"
#import "GLTollStationSectionHeaderView.h"
#import "UIView+Addition.h"
#import "MJRefresh.h"
#import "CJCalendarViewController.h"
#import "MonthChargeViewController.h"
#import "NSDate+Extension.h"
#import "RequestHelper.h"
#import "RequestGinsengModel.h"
#import "RequestOutginseng.h"
#import "ParModel.h"
#import "TollStationChargeSummaryModel.h"
#import "MJExtension.h"
#import "TollStationChargeListModel.h"
#import "SVProgressHUD.h"
#import "EKPopMenuView.h"
#import "RightCodeTool.h"
#import "EKCalendarView.h"
#import "NSDate+Extension.h"

@interface GLTollStationDataListViewController ()<CalendarViewControllerDelegate>

@property (nonatomic, strong)GLTollStationSectionHeaderView *stationHeaderV;
@property (nonatomic,   copy)NSString *currenYDMStr; // 当前显示的日期 yyyy-MM-dd
@property (nonatomic, strong)NSMutableArray *popMenuDateArr;
@property (nonatomic, strong)TollStationChargeSummaryModel *summaryModel;
@property (nonatomic, strong) UIDatePicker *myDatePicker;
@property(nonatomic,strong)UIView*pickerView;
@property(nonatomic,strong)UIView*alphaView;


@end

static NSString *cellID = @"tollStationDataCell";
@implementation GLTollStationDataListViewController

- (void)setUpMenuDataArray {
    _popMenuDateArr = [NSMutableArray array];
}

#pragma      ---------事件管理   收费数据界面


- (void)viewDidLoad {
    [super viewDidLoad];
    [SVProgressHUD dismiss];
    [self setUpNavigationbar];
//    if ([[RightCodeTool sharedTool] rightIsEqualTO:@"P0405"]) {
        [self setUpTableView];
        [self setUpMenuDataArray];
        [self caculateMenuData];
        _summaryModel = [[TollStationChargeSummaryModel alloc] init];
        //初始化开始时间
        NSDate *nowDate = [NSDate dateYesterday];
        NSString *nowStr = [nowDate stringWithFormat:@"yyyy-MM-dd"];
        _currenYDMStr = nowStr;
    [self loadNewData];

    RegisterNotify(GLStationChargeReportNotification, @selector(requestAgain));
}
- (void)dealloc {
    RemoveNofify
}

- (void) requestAgain {
    [self fetchNewServer];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    self.navigationController.
}

- (void) setUpNavigationbar {
    
}

//设置界面数据
- (void) caculateDate {
    NSDate *nowDate = [NSDate dateYesterday];
    NSString *nowStr = [nowDate stringWithFormat:@"yyyy-MM-dd"];
    _currenYDMStr = nowStr;
    NSArray *tempArr = [nowStr componentsSeparatedByString:@"-"];
    NSString *yDMStr = [NSString stringWithFormat:@"%@年%@月%@日",tempArr[0],tempArr[1],tempArr[2]];
    [self setUpShowDate:yDMStr];
}

- (void) caculateMenuData{ // yyyy年MM月
    NSDate *nowDate = [NSDate date];
    NSString *nowSr = [nowDate stringWithFormat:@"yyyy-MM"];
    NSArray *tempArr = [nowSr componentsSeparatedByString:@"-"];
    NSString *yStr = tempArr[0];
    NSString *mStr = tempArr[1];
    NSString *lastYStr = [NSString stringWithFormat:@"%d",[yStr intValue]-1];
    //今年的月份
    //NSMutableArray *thisYear = [[NSMutableArray alloc] init];
    for (int i = [mStr intValue]; i > 0; i--) {
        NSString *tempStr = [NSString stringWithFormat:@"%@年%02d月",yStr,i];
        [_popMenuDateArr addObject:tempStr];
    }
    //去年的月份
    for (int i = 12; i >= [mStr intValue] ; i --) {
        NSString *tempStr = [NSString stringWithFormat:@"%@年%02d月",lastYStr,i];
        [_popMenuDateArr addObject:tempStr];
    }
}

- (void) setUpTableView {
    self.tableView.contentInset          = UIEdgeInsetsMake(0, 0, 50, 0);
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    [self.tableView registerNib:[UINib nibWithNibName:@"GLTollStationDataCell" bundle:nil] forCellReuseIdentifier:cellID];
    self.tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tableView.delegate   = self;
    self.tableView.dataSource = self;
}

//加载新数据
- (void) loadNewData {
//    [SVProgressHUD showWithStatus:@"正在加载中..."];
    [self fetchNewServer];
    [self.tableView.mj_header endRefreshing];
}

- (NSString *) appdenString:(NSString *)str {
    NSString *valueStr =[NSString stringWithFormat:@"[{\"key\":\"ChargeDate\",\"value\":\"%@\"}]",str];
    return valueStr;
}

//加载新数据
- (void)fetchNewServer {
    //[SVProgressHUD showWithStatus:@"正在加载中..."];
//    [self];
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *getAllModel=[[RequestGinsengModel alloc] init];
    getAllModel.URL          = GetEventDataURL;
    getAllModel.MethodName    = @"SearchTollStationChargeByDate";
    getAllModel.UpdatedTime   = @"";
    getAllModel.SystemCode    = @"GuangleHighway";
    getAllModel.DataValue    = [self appdenString:_currenYDMStr];
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel) {
        
        if ([requestOutginseng.Code isEqualToString:@"001"]) { //收费事件
            _summaryModel = [TollStationChargeSummaryModel mj_objectWithKeyValues:requestOutginseng.DataValue];
        }
        
       [self.stationHeaderV refreshChargeLabelText:_summaryModel.TotalCharge vehicleFlow:_summaryModel.TotalTrafficFlow];
        [self.tableView reloadData];
        [SVProgressHUD dismiss];
       //[self caculateDate];
    };
    [requestHelper RequestGinsengModel:getAllModel andPushController:self];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _summaryModel.TollStationChargeList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    GLTollStationDataCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    TollStationChargeListModel *model = _summaryModel.TollStationChargeList[indexPath.row];
    cell.stationSumaryM = model;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    __weak __typeof(&*self)weakSelf = self;
    if (_stationHeaderV == nil) {
        _stationHeaderV = [[GLTollStationSectionHeaderView alloc]initGLStationSectionView:CGRectMake(0, 0, self.view.width, 50)];
         [self caculateDate];
    }
    
    _stationHeaderV.btnClickBlock = ^(BOOL show){
        if (show) {
            [weakSelf setUpCalendaerVC];
        }
    };
    return _stationHeaderV;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 110;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([[RightCodeTool sharedTool] rightIsEqualTO:@"P040501"]) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        // 2. 创建下一个控制器
        MonthChargeViewController *monthVc = [[MonthChargeViewController alloc] init];
        TollStationChargeListModel *chargeModel=_summaryModel.TollStationChargeList[indexPath.row];
        monthVc.TollStationUID = chargeModel.TollStationUID;
        monthVc.popMenuDataArr = _popMenuDateArr;
        monthVc.stationName    = chargeModel.TollStationName;
        monthVc.dateString    = _currenYDMStr;
        [self.navigationController pushViewController:monthVc animated:YES];
    } else {
        [SVProgressHUD showErrorWithStatus:@"没有查看收费数据的权限"];
    }
    
}

#pragma mark - 日历
- (void) setUpCalendaerVC {
    EKCalendarView *calendar = [[EKCalendarView alloc] initWithDatePosition:EKCalendarMiddel CompleteBlock:^(NSDate *startDate) {
        if (startDate != nil) {
            _currenYDMStr = [startDate stringWithFormat:@"yyyy-MM-dd"];
            NSArray*dateArray= [_currenYDMStr componentsSeparatedByString:@"-"];
            NSString *yDMStr = [NSString stringWithFormat:@"%@年%@月%@日",dateArray[0],dateArray[1],dateArray[2]];
            [self setUpShowDate:yDMStr];
            self.stationHeaderV.isSelectCanderBtn = NO;
            [self loadNewData];
        }
        
    }];
    [calendar dismissHandler:^(BOOL isCanceled) {
        self.stationHeaderV.isSelectCanderBtn = NO;
    }];
    [calendar show];
   
//    UIWindow*window=[UIApplication sharedApplication].windows[0];
//    if (!self.alphaView) {
//        self.alphaView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, window.bounds.size.width, window.bounds.size.height)];
//        self.alphaView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
//        
//        [window addSubview:self.alphaView];
//        
//        self.pickerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width-100, 280)];
//        self.pickerView.center = self.view.center;
//        self.pickerView.backgroundColor=[UIColor whiteColor];
//        [self.alphaView addSubview:self.pickerView];
//        
//        self.myDatePicker = [[UIDatePicker alloc] init];
//        self.myDatePicker.frame=CGRectMake(10, 10, self.view.bounds.size.width-120, 250);
//        self.myDatePicker.datePickerMode = UIDatePickerModeDate;
//        [self.myDatePicker setLocale:[NSLocale localeWithLocaleIdentifier:@"zh-CN"]];
//        [self.pickerView addSubview:self.myDatePicker];
//        
//        [self.myDatePicker addTarget:self
//                              action:@selector(datePickerDateChanged:)
//                    forControlEvents:UIControlEventValueChanged];
//        
//        NSTimeInterval minYearTime = -365 * 24 * 60 * 60;
//        NSTimeInterval maxYearTime = -1 * 24 * 60 * 60;
//        NSDate *todayDate = [NSDate date];
//        NSDate *oneYearFromToday = [todayDate dateByAddingTimeInterval:minYearTime];
//        NSDate *twoYearsFromToday = [todayDate dateByAddingTimeInterval:maxYearTime];
//        self.myDatePicker.minimumDate = oneYearFromToday;
//        self.myDatePicker.maximumDate = twoYearsFromToday;
//        
//        UIButton*cancelBtn=[UIButton buttonWithType:UIButtonTypeCustom];
//        cancelBtn.frame=CGRectMake(20, 240, 80, 30);
//        [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
//        cancelBtn.layer.cornerRadius=3;
//        [cancelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//        cancelBtn.layer.borderColor=[UIColor blackColor].CGColor;
//        cancelBtn.layer.borderWidth=0.5;
//        [cancelBtn addTarget:self action:@selector(canclePickerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//        [self.pickerView addSubview:cancelBtn];
//        
//        UIButton*sureBtn=[UIButton buttonWithType:UIButtonTypeCustom];
//        sureBtn.frame=CGRectMake(self.pickerView.bounds.size.width-100, 240, 80, 30);
//        [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
//        [sureBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//        sureBtn.layer.cornerRadius=3;
//        sureBtn.layer.borderColor=[UIColor blackColor].CGColor;
//        sureBtn.layer.borderWidth=0.5;
//        [sureBtn addTarget:self action:@selector(surePickerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//        [self.pickerView addSubview:sureBtn];
//
//    }
//    else
//    {
//        [window addSubview:self.alphaView];
//    }
}

//-(void)canclePickerBtnClick:(UIButton*)btn
//{
//     self.stationHeaderV.isSelectCanderBtn = NO;
//    [self.alphaView removeFromSuperview];
//}
//
//-(void)surePickerBtnClick:(UIButton*)btn
//{
//    NSDateFormatter*dateFormatter=[[NSDateFormatter alloc]init];
//    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
//   _currenYDMStr =[dateFormatter stringFromDate:self.myDatePicker.date];
//   NSArray*dateArray= [_currenYDMStr componentsSeparatedByString:@"-"];
//    NSString *yDMStr = [NSString stringWithFormat:@"%@年%@月%@日",dateArray[0],dateArray[1],dateArray[2]];
//    [self setUpShowDate:yDMStr];
//    
//    [self loadNewData];
//    self.stationHeaderV.isSelectCanderBtn = NO;
//    [self.alphaView removeFromSuperview];
//}
//
//- (void) datePickerDateChanged:(UIDatePicker *)paramDatePicker {
//    if ([paramDatePicker isEqual:self.myDatePicker]) {
//        NSLog(@"Selected date = %@", paramDatePicker.date);
//    }
//}


- (void) setUpShowDate:(NSString *)str {
    [self.stationHeaderV refreshBtnTitleString:str];
}


@end
